package com.relatev.minecraft.TRMobSpawn.listener;

import com.relatev.minecraft.TRMobAPI.TRLevelMob;
import com.relatev.minecraft.TRMobAPI.TRMob;
import com.relatev.minecraft.TRMobAPI.TRMobAPI;
import com.relatev.minecraft.TRMobSpawn.ConfigManager;
import com.relatev.minecraft.TRMobSpawn.TRMobInfo;
import com.relatev.minecraft.TRMobSpawn.TRMobSpawn;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;

public class SpawnListener implements Listener {

    private static SpawnListener Instance;
    private static Random random;

    public static void init() {
        random = new Random();
        Instance = new SpawnListener();
        Bukkit.getPluginManager().registerEvents(Instance, TRMobSpawn.MainPlugin);
    }

    @EventHandler
    public void onSpawn(CreatureSpawnEvent event) {
        if (event.getSpawnReason() != SpawnReason.CUSTOM) {
            TRMobInfo trmi = ConfigManager.getSpawnInfo(event.getLocation().getWorld(), event.getEntityType());
            if (trmi != null) {
                event.setCancelled(true);
                TRMob trm = TRMobAPI.getAPI().getTRMobManager().getTRMob(trmi.TRMobID);
                if (trm != null) {
                    if (trm instanceof TRLevelMob) {
                        ((TRLevelMob) trm).spawn(event.getLocation(), trmi.MinLevel + random.nextInt(trmi.MaxLevel - trmi.MinLevel + 1));
                    } else {
                        trm.spawn(event.getLocation());
                    }
                }
            }
        }
    }
}
